home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / codecs.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  33.1 KB  |  1,025 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import __builtin__
  13. import sys
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError('Failed to load the builtin codecs: %s' % why)
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE',
  33.     'BOM_UTF8',
  34.     'BOM_UTF16',
  35.     'BOM_UTF16_LE',
  36.     'BOM_UTF16_BE',
  37.     'BOM_UTF32',
  38.     'BOM_UTF32_LE',
  39.     'BOM_UTF32_BE',
  40.     'strict_errors',
  41.     'ignore_errors',
  42.     'replace_errors',
  43.     'xmlcharrefreplace_errors',
  44.     'register_error',
  45.     'lookup_error']
  46. BOM_UTF8 = '\xef\xbb\xbf'
  47. BOM_LE = BOM_UTF16_LE = '\xff\xfe'
  48. BOM_BE = BOM_UTF16_BE = '\xfe\xff'
  49. BOM_UTF32_LE = '\xff\xfe\x00\x00'
  50. BOM_UTF32_BE = '\x00\x00\xfe\xff'
  51. if sys.byteorder == 'little':
  52.     BOM = BOM_UTF16 = BOM_UTF16_LE
  53.     BOM_UTF32 = BOM_UTF32_LE
  54. else:
  55.     BOM = BOM_UTF16 = BOM_UTF16_BE
  56.     BOM_UTF32 = BOM_UTF32_BE
  57. BOM32_LE = BOM_UTF16_LE
  58. BOM32_BE = BOM_UTF16_BE
  59. BOM64_LE = BOM_UTF32_LE
  60. BOM64_BE = BOM_UTF32_BE
  61.  
  62. class CodecInfo(tuple):
  63.     
  64.     def __new__(cls, encode, decode, streamreader = None, streamwriter = None, incrementalencoder = None, incrementaldecoder = None, name = None):
  65.         self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  66.         self.name = name
  67.         self.encode = encode
  68.         self.decode = decode
  69.         self.incrementalencoder = incrementalencoder
  70.         self.incrementaldecoder = incrementaldecoder
  71.         self.streamwriter = streamwriter
  72.         self.streamreader = streamreader
  73.         return self
  74.  
  75.     
  76.     def __repr__(self):
  77.         return '<%s.%s object for encoding %s at 0x%x>' % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
  78.  
  79.  
  80.  
  81. class Codec:
  82.     """ Defines the interface for stateless encoders/decoders.
  83.  
  84.         The .encode()/.decode() methods may use different error
  85.         handling schemes by providing the errors argument. These
  86.         string values are predefined:
  87.  
  88.          'strict' - raise a ValueError error (or a subclass)
  89.          'ignore' - ignore the character and continue with the next
  90.          'replace' - replace with a suitable replacement character;
  91.                     Python will use the official U+FFFD REPLACEMENT
  92.                     CHARACTER for the builtin Unicode codecs on
  93.                     decoding and '?' on encoding.
  94.          'xmlcharrefreplace' - Replace with the appropriate XML
  95.                                character reference (only for encoding).
  96.          'backslashreplace'  - Replace with backslashed escape sequences
  97.                                (only for encoding).
  98.  
  99.         The set of allowed values can be extended via register_error.
  100.  
  101.     """
  102.     
  103.     def encode(self, input, errors = 'strict'):
  104.         """ Encodes the object input and returns a tuple (output
  105.             object, length consumed).
  106.  
  107.             errors defines the error handling to apply. It defaults to
  108.             'strict' handling.
  109.  
  110.             The method may not store state in the Codec instance. Use
  111.             StreamCodec for codecs which have to keep state in order to
  112.             make encoding/decoding efficient.
  113.  
  114.             The encoder must be able to handle zero length input and
  115.             return an empty object of the output object type in this
  116.             situation.
  117.  
  118.         """
  119.         raise NotImplementedError
  120.  
  121.     
  122.     def decode(self, input, errors = 'strict'):
  123.         """ Decodes the object input and returns a tuple (output
  124.             object, length consumed).
  125.  
  126.             input must be an object which provides the bf_getreadbuf
  127.             buffer slot. Python strings, buffer objects and memory
  128.             mapped files are examples of objects providing this slot.
  129.  
  130.             errors defines the error handling to apply. It defaults to
  131.             'strict' handling.
  132.  
  133.             The method may not store state in the Codec instance. Use
  134.             StreamCodec for codecs which have to keep state in order to
  135.             make encoding/decoding efficient.
  136.  
  137.             The decoder must be able to handle zero length input and
  138.             return an empty object of the output object type in this
  139.             situation.
  140.  
  141.         """
  142.         raise NotImplementedError
  143.  
  144.  
  145.  
  146. class IncrementalEncoder(object):
  147.     '''
  148.     An IncrementalEncoder encodes an input in multiple steps. The input can be
  149.     passed piece by piece to the encode() method. The IncrementalEncoder remembers
  150.     the state of the Encoding process between calls to encode().
  151.     '''
  152.     
  153.     def __init__(self, errors = 'strict'):
  154.         '''
  155.         Creates an IncrementalEncoder instance.
  156.  
  157.         The IncrementalEncoder may use different error handling schemes by
  158.         providing the errors keyword argument. See the module docstring
  159.         for a list of possible values.
  160.         '''
  161.         self.errors = errors
  162.         self.buffer = ''
  163.  
  164.     
  165.     def encode(self, input, final = False):
  166.         '''
  167.         Encodes input and returns the resulting object.
  168.         '''
  169.         raise NotImplementedError
  170.  
  171.     
  172.     def reset(self):
  173.         '''
  174.         Resets the encoder to the initial state.
  175.         '''
  176.         pass
  177.  
  178.  
  179.  
  180. class BufferedIncrementalEncoder(IncrementalEncoder):
  181.     '''
  182.     This subclass of IncrementalEncoder can be used as the baseclass for an
  183.     incremental encoder if the encoder must keep some of the output in a
  184.     buffer between calls to encode().
  185.     '''
  186.     
  187.     def __init__(self, errors = 'strict'):
  188.         IncrementalEncoder.__init__(self, errors)
  189.         self.buffer = ''
  190.  
  191.     
  192.     def _buffer_encode(self, input, errors, final):
  193.         raise NotImplementedError
  194.  
  195.     
  196.     def encode(self, input, final = False):
  197.         data = self.buffer + input
  198.         (result, consumed) = self._buffer_encode(data, self.errors, final)
  199.         self.buffer = data[consumed:]
  200.         return result
  201.  
  202.     
  203.     def reset(self):
  204.         IncrementalEncoder.reset(self)
  205.         self.buffer = ''
  206.  
  207.  
  208.  
  209. class IncrementalDecoder(object):
  210.     '''
  211.     An IncrementalDecoder decodes an input in multiple steps. The input can be
  212.     passed piece by piece to the decode() method. The IncrementalDecoder
  213.     remembers the state of the decoding process between calls to decode().
  214.     '''
  215.     
  216.     def __init__(self, errors = 'strict'):
  217.         '''
  218.         Creates a IncrementalDecoder instance.
  219.  
  220.         The IncrementalDecoder may use different error handling schemes by
  221.         providing the errors keyword argument. See the module docstring
  222.         for a list of possible values.
  223.         '''
  224.         self.errors = errors
  225.  
  226.     
  227.     def decode(self, input, final = False):
  228.         '''
  229.         Decodes input and returns the resulting object.
  230.         '''
  231.         raise NotImplementedError
  232.  
  233.     
  234.     def reset(self):
  235.         '''
  236.         Resets the decoder to the initial state.
  237.         '''
  238.         pass
  239.  
  240.  
  241.  
  242. class BufferedIncrementalDecoder(IncrementalDecoder):
  243.     '''
  244.     This subclass of IncrementalDecoder can be used as the baseclass for an
  245.     incremental decoder if the decoder must be able to handle incomplete byte
  246.     sequences.
  247.     '''
  248.     
  249.     def __init__(self, errors = 'strict'):
  250.         IncrementalDecoder.__init__(self, errors)
  251.         self.buffer = ''
  252.  
  253.     
  254.     def _buffer_decode(self, input, errors, final):
  255.         raise NotImplementedError
  256.  
  257.     
  258.     def decode(self, input, final = False):
  259.         data = self.buffer + input
  260.         (result, consumed) = self._buffer_decode(data, self.errors, final)
  261.         self.buffer = data[consumed:]
  262.         return result
  263.  
  264.     
  265.     def reset(self):
  266.         IncrementalDecoder.reset(self)
  267.         self.buffer = ''
  268.  
  269.  
  270.  
  271. class StreamWriter(Codec):
  272.     
  273.     def __init__(self, stream, errors = 'strict'):
  274.         """ Creates a StreamWriter instance.
  275.  
  276.             stream must be a file-like object open for writing
  277.             (binary) data.
  278.  
  279.             The StreamWriter may use different error handling
  280.             schemes by providing the errors keyword argument. These
  281.             parameters are predefined:
  282.  
  283.              'strict' - raise a ValueError (or a subclass)
  284.              'ignore' - ignore the character and continue with the next
  285.              'replace'- replace with a suitable replacement character
  286.              'xmlcharrefreplace' - Replace with the appropriate XML
  287.                                    character reference.
  288.              'backslashreplace'  - Replace with backslashed escape
  289.                                    sequences (only for encoding).
  290.  
  291.             The set of allowed parameter values can be extended via
  292.             register_error.
  293.         """
  294.         self.stream = stream
  295.         self.errors = errors
  296.  
  297.     
  298.     def write(self, object):
  299.         """ Writes the object's contents encoded to self.stream.
  300.         """
  301.         (data, consumed) = self.encode(object, self.errors)
  302.         self.stream.write(data)
  303.  
  304.     
  305.     def writelines(self, list):
  306.         ''' Writes the concatenated list of strings to the stream
  307.             using .write().
  308.         '''
  309.         self.write(''.join(list))
  310.  
  311.     
  312.     def reset(self):
  313.         ''' Flushes and resets the codec buffers used for keeping state.
  314.  
  315.             Calling this method should ensure that the data on the
  316.             output is put into a clean state, that allows appending
  317.             of new fresh data without having to rescan the whole
  318.             stream to recover state.
  319.  
  320.         '''
  321.         pass
  322.  
  323.     
  324.     def __getattr__(self, name, getattr = getattr):
  325.         ''' Inherit all other methods from the underlying stream.
  326.         '''
  327.         return getattr(self.stream, name)
  328.  
  329.     
  330.     def __enter__(self):
  331.         return self
  332.  
  333.     
  334.     def __exit__(self, type, value, tb):
  335.         self.stream.close()
  336.  
  337.  
  338.  
  339. class StreamReader(Codec):
  340.     
  341.     def __init__(self, stream, errors = 'strict'):
  342.         """ Creates a StreamReader instance.
  343.  
  344.             stream must be a file-like object open for reading
  345.             (binary) data.
  346.  
  347.             The StreamReader may use different error handling
  348.             schemes by providing the errors keyword argument. These
  349.             parameters are predefined:
  350.  
  351.              'strict' - raise a ValueError (or a subclass)
  352.              'ignore' - ignore the character and continue with the next
  353.              'replace'- replace with a suitable replacement character;
  354.  
  355.             The set of allowed parameter values can be extended via
  356.             register_error.
  357.         """
  358.         self.stream = stream
  359.         self.errors = errors
  360.         self.bytebuffer = ''
  361.         self.charbuffer = ''
  362.         self.linebuffer = None
  363.  
  364.     
  365.     def decode(self, input, errors = 'strict'):
  366.         raise NotImplementedError
  367.  
  368.     
  369.     def read(self, size = -1, chars = -1, firstline = False):
  370.         ''' Decodes data from the stream self.stream and returns the
  371.             resulting object.
  372.  
  373.             chars indicates the number of characters to read from the
  374.             stream. read() will never return more than chars
  375.             characters, but it might return less, if there are not enough
  376.             characters available.
  377.  
  378.             size indicates the approximate maximum number of bytes to
  379.             read from the stream for decoding purposes. The decoder
  380.             can modify this setting as appropriate. The default value
  381.             -1 indicates to read and decode as much as possible.  size
  382.             is intended to prevent having to decode huge files in one
  383.             step.
  384.  
  385.             If firstline is true, and a UnicodeDecodeError happens
  386.             after the first line terminator in the input only the first line
  387.             will be returned, the rest of the input will be kept until the
  388.             next call to read().
  389.  
  390.             The method should use a greedy read strategy meaning that
  391.             it should read as much data as is allowed within the
  392.             definition of the encoding and the given size, e.g.  if
  393.             optional encoding endings or state markers are available
  394.             on the stream, these should be read too.
  395.         '''
  396.         if self.linebuffer:
  397.             self.charbuffer = ''.join(self.linebuffer)
  398.             self.linebuffer = None
  399.         
  400.         while True:
  401.             if chars < 0:
  402.                 if size < 0:
  403.                     if self.charbuffer:
  404.                         break
  405.                     
  406.                 elif len(self.charbuffer) >= size:
  407.                     break
  408.                 
  409.             elif len(self.charbuffer) >= chars:
  410.                 break
  411.             
  412.             if size < 0:
  413.                 newdata = self.stream.read()
  414.             else:
  415.                 newdata = self.stream.read(size)
  416.             data = self.bytebuffer + newdata
  417.             
  418.             try:
  419.                 (newchars, decodedbytes) = self.decode(data, self.errors)
  420.             except UnicodeDecodeError:
  421.                 exc = None
  422.                 if firstline:
  423.                     (newchars, decodedbytes) = self.decode(data[:exc.start], self.errors)
  424.                     lines = newchars.splitlines(True)
  425.                     if len(lines) <= 1:
  426.                         raise 
  427.                     
  428.                 else:
  429.                     raise 
  430.             except:
  431.                 firstline
  432.  
  433.             self.bytebuffer = data[decodedbytes:]
  434.             self.charbuffer += newchars
  435.             if not newdata:
  436.                 break
  437.                 continue
  438.             self
  439.         if chars < 0:
  440.             result = self.charbuffer
  441.             self.charbuffer = ''
  442.         else:
  443.             result = self.charbuffer[:chars]
  444.             self.charbuffer = self.charbuffer[chars:]
  445.         return result
  446.  
  447.     
  448.     def readline(self, size = None, keepends = True):
  449.         ''' Read one line from the input stream and return the
  450.             decoded data.
  451.  
  452.             size, if given, is passed as size argument to the
  453.             read() method.
  454.  
  455.         '''
  456.         if self.linebuffer:
  457.             line = self.linebuffer[0]
  458.             del self.linebuffer[0]
  459.             if len(self.linebuffer) == 1:
  460.                 self.charbuffer = self.linebuffer[0]
  461.                 self.linebuffer = None
  462.             
  463.             if not keepends:
  464.                 line = line.splitlines(False)[0]
  465.             
  466.             return line
  467.         
  468.         if not size:
  469.             pass
  470.         readsize = 72
  471.         line = ''
  472.         while True:
  473.             data = self.read(readsize, firstline = True)
  474.             if data:
  475.                 if data.endswith('\r'):
  476.                     data += self.read(size = 1, chars = 1)
  477.                 
  478.             
  479.             line += data
  480.             lines = line.splitlines(True)
  481.             if lines:
  482.                 if len(lines) > 1:
  483.                     line = lines[0]
  484.                     del lines[0]
  485.                     if len(lines) > 1:
  486.                         lines[-1] += self.charbuffer
  487.                         self.linebuffer = lines
  488.                         self.charbuffer = None
  489.                     else:
  490.                         self.charbuffer = lines[0] + self.charbuffer
  491.                     if not keepends:
  492.                         line = line.splitlines(False)[0]
  493.                     
  494.                     break
  495.                 
  496.                 line0withend = lines[0]
  497.                 line0withoutend = lines[0].splitlines(False)[0]
  498.                 if line0withend != line0withoutend:
  499.                     self.charbuffer = ''.join(lines[1:]) + self.charbuffer
  500.                     if keepends:
  501.                         line = line0withend
  502.                     else:
  503.                         line = line0withoutend
  504.                     break
  505.                 
  506.             
  507.             if not data or size is not None:
  508.                 if line and not keepends:
  509.                     line = line.splitlines(False)[0]
  510.                 
  511.                 break
  512.             
  513.             if readsize < 8000:
  514.                 readsize *= 2
  515.                 continue
  516.         return line
  517.  
  518.     
  519.     def readlines(self, sizehint = None, keepends = True):
  520.         """ Read all lines available on the input stream
  521.             and return them as list of lines.
  522.  
  523.             Line breaks are implemented using the codec's decoder
  524.             method and are included in the list entries.
  525.  
  526.             sizehint, if given, is ignored since there is no efficient
  527.             way to finding the true end-of-line.
  528.  
  529.         """
  530.         data = self.read()
  531.         return data.splitlines(keepends)
  532.  
  533.     
  534.     def reset(self):
  535.         ''' Resets the codec buffers used for keeping state.
  536.  
  537.             Note that no stream repositioning should take place.
  538.             This method is primarily intended to be able to recover
  539.             from decoding errors.
  540.  
  541.         '''
  542.         self.bytebuffer = ''
  543.         self.charbuffer = u''
  544.         self.linebuffer = None
  545.  
  546.     
  547.     def seek(self, offset, whence = 0):
  548.         """ Set the input stream's current position.
  549.  
  550.             Resets the codec buffers used for keeping state.
  551.         """
  552.         self.reset()
  553.         self.stream.seek(offset, whence)
  554.  
  555.     
  556.     def next(self):
  557.         ''' Return the next decoded line from the input stream.'''
  558.         line = self.readline()
  559.         if line:
  560.             return line
  561.         
  562.         raise StopIteration
  563.  
  564.     
  565.     def __iter__(self):
  566.         return self
  567.  
  568.     
  569.     def __getattr__(self, name, getattr = getattr):
  570.         ''' Inherit all other methods from the underlying stream.
  571.         '''
  572.         return getattr(self.stream, name)
  573.  
  574.     
  575.     def __enter__(self):
  576.         return self
  577.  
  578.     
  579.     def __exit__(self, type, value, tb):
  580.         self.stream.close()
  581.  
  582.  
  583.  
  584. class StreamReaderWriter:
  585.     ''' StreamReaderWriter instances allow wrapping streams which
  586.         work in both read and write modes.
  587.  
  588.         The design is such that one can use the factory functions
  589.         returned by the codec.lookup() function to construct the
  590.         instance.
  591.  
  592.     '''
  593.     encoding = 'unknown'
  594.     
  595.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  596.         ''' Creates a StreamReaderWriter instance.
  597.  
  598.             stream must be a Stream-like object.
  599.  
  600.             Reader, Writer must be factory functions or classes
  601.             providing the StreamReader, StreamWriter interface resp.
  602.  
  603.             Error handling is done in the same way as defined for the
  604.             StreamWriter/Readers.
  605.  
  606.         '''
  607.         self.stream = stream
  608.         self.reader = Reader(stream, errors)
  609.         self.writer = Writer(stream, errors)
  610.         self.errors = errors
  611.  
  612.     
  613.     def read(self, size = -1):
  614.         return self.reader.read(size)
  615.  
  616.     
  617.     def readline(self, size = None):
  618.         return self.reader.readline(size)
  619.  
  620.     
  621.     def readlines(self, sizehint = None):
  622.         return self.reader.readlines(sizehint)
  623.  
  624.     
  625.     def next(self):
  626.         ''' Return the next decoded line from the input stream.'''
  627.         return self.reader.next()
  628.  
  629.     
  630.     def __iter__(self):
  631.         return self
  632.  
  633.     
  634.     def write(self, data):
  635.         return self.writer.write(data)
  636.  
  637.     
  638.     def writelines(self, list):
  639.         return self.writer.writelines(list)
  640.  
  641.     
  642.     def reset(self):
  643.         self.reader.reset()
  644.         self.writer.reset()
  645.  
  646.     
  647.     def __getattr__(self, name, getattr = getattr):
  648.         ''' Inherit all other methods from the underlying stream.
  649.         '''
  650.         return getattr(self.stream, name)
  651.  
  652.     
  653.     def __enter__(self):
  654.         return self
  655.  
  656.     
  657.     def __exit__(self, type, value, tb):
  658.         self.stream.close()
  659.  
  660.  
  661.  
  662. class StreamRecoder:
  663.     ''' StreamRecoder instances provide a frontend - backend
  664.         view of encoding data.
  665.  
  666.         They use the complete set of APIs returned by the
  667.         codecs.lookup() function to implement their task.
  668.  
  669.         Data written to the stream is first decoded into an
  670.         intermediate format (which is dependent on the given codec
  671.         combination) and then written to the stream using an instance
  672.         of the provided Writer class.
  673.  
  674.         In the other direction, data is read from the stream using a
  675.         Reader instance and then return encoded data to the caller.
  676.  
  677.     '''
  678.     data_encoding = 'unknown'
  679.     file_encoding = 'unknown'
  680.     
  681.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  682.         ''' Creates a StreamRecoder instance which implements a two-way
  683.             conversion: encode and decode work on the frontend (the
  684.             input to .read() and output of .write()) while
  685.             Reader and Writer work on the backend (reading and
  686.             writing to the stream).
  687.  
  688.             You can use these objects to do transparent direct
  689.             recodings from e.g. latin-1 to utf-8 and back.
  690.  
  691.             stream must be a file-like object.
  692.  
  693.             encode, decode must adhere to the Codec interface, Reader,
  694.             Writer must be factory functions or classes providing the
  695.             StreamReader, StreamWriter interface resp.
  696.  
  697.             encode and decode are needed for the frontend translation,
  698.             Reader and Writer for the backend translation. Unicode is
  699.             used as intermediate encoding.
  700.  
  701.             Error handling is done in the same way as defined for the
  702.             StreamWriter/Readers.
  703.  
  704.         '''
  705.         self.stream = stream
  706.         self.encode = encode
  707.         self.decode = decode
  708.         self.reader = Reader(stream, errors)
  709.         self.writer = Writer(stream, errors)
  710.         self.errors = errors
  711.  
  712.     
  713.     def read(self, size = -1):
  714.         data = self.reader.read(size)
  715.         (data, bytesencoded) = self.encode(data, self.errors)
  716.         return data
  717.  
  718.     
  719.     def readline(self, size = None):
  720.         if size is None:
  721.             data = self.reader.readline()
  722.         else:
  723.             data = self.reader.readline(size)
  724.         (data, bytesencoded) = self.encode(data, self.errors)
  725.         return data
  726.  
  727.     
  728.     def readlines(self, sizehint = None):
  729.         data = self.reader.read()
  730.         (data, bytesencoded) = self.encode(data, self.errors)
  731.         return data.splitlines(1)
  732.  
  733.     
  734.     def next(self):
  735.         ''' Return the next decoded line from the input stream.'''
  736.         data = self.reader.next()
  737.         (data, bytesencoded) = self.encode(data, self.errors)
  738.         return data
  739.  
  740.     
  741.     def __iter__(self):
  742.         return self
  743.  
  744.     
  745.     def write(self, data):
  746.         (data, bytesdecoded) = self.decode(data, self.errors)
  747.         return self.writer.write(data)
  748.  
  749.     
  750.     def writelines(self, list):
  751.         data = ''.join(list)
  752.         (data, bytesdecoded) = self.decode(data, self.errors)
  753.         return self.writer.write(data)
  754.  
  755.     
  756.     def reset(self):
  757.         self.reader.reset()
  758.         self.writer.reset()
  759.  
  760.     
  761.     def __getattr__(self, name, getattr = getattr):
  762.         ''' Inherit all other methods from the underlying stream.
  763.         '''
  764.         return getattr(self.stream, name)
  765.  
  766.     
  767.     def __enter__(self):
  768.         return self
  769.  
  770.     
  771.     def __exit__(self, type, value, tb):
  772.         self.stream.close()
  773.  
  774.  
  775.  
  776. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  777.     """ Open an encoded file using the given mode and return
  778.         a wrapped version providing transparent encoding/decoding.
  779.  
  780.         Note: The wrapped version will only accept the object format
  781.         defined by the codecs, i.e. Unicode objects for most builtin
  782.         codecs. Output is also codec dependent and will usually be
  783.         Unicode as well.
  784.  
  785.         Files are always opened in binary mode, even if no binary mode
  786.         was specified. This is done to avoid data loss due to encodings
  787.         using 8-bit values. The default file mode is 'rb' meaning to
  788.         open the file in binary read mode.
  789.  
  790.         encoding specifies the encoding which is to be used for the
  791.         file.
  792.  
  793.         errors may be given to define the error handling. It defaults
  794.         to 'strict' which causes ValueErrors to be raised in case an
  795.         encoding error occurs.
  796.  
  797.         buffering has the same meaning as for the builtin open() API.
  798.         It defaults to line buffered.
  799.  
  800.         The returned wrapped file object provides an extra attribute
  801.         .encoding which allows querying the used encoding. This
  802.         attribute is only available if an encoding was specified as
  803.         parameter.
  804.  
  805.     """
  806.     if encoding is not None and 'b' not in mode:
  807.         mode = mode + 'b'
  808.     
  809.     file = __builtin__.open(filename, mode, buffering)
  810.     if encoding is None:
  811.         return file
  812.     
  813.     info = lookup(encoding)
  814.     srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  815.     srw.encoding = encoding
  816.     return srw
  817.  
  818.  
  819. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  820.     """ Return a wrapped version of file which provides transparent
  821.         encoding translation.
  822.  
  823.         Strings written to the wrapped file are interpreted according
  824.         to the given data_encoding and then written to the original
  825.         file as string using file_encoding. The intermediate encoding
  826.         will usually be Unicode but depends on the specified codecs.
  827.  
  828.         Strings are read from the file using file_encoding and then
  829.         passed back to the caller as string using data_encoding.
  830.  
  831.         If file_encoding is not given, it defaults to data_encoding.
  832.  
  833.         errors may be given to define the error handling. It defaults
  834.         to 'strict' which causes ValueErrors to be raised in case an
  835.         encoding error occurs.
  836.  
  837.         The returned wrapped file object provides two extra attributes
  838.         .data_encoding and .file_encoding which reflect the given
  839.         parameters of the same name. The attributes can be used for
  840.         introspection by Python programs.
  841.  
  842.     """
  843.     if file_encoding is None:
  844.         file_encoding = data_encoding
  845.     
  846.     data_info = lookup(data_encoding)
  847.     file_info = lookup(file_encoding)
  848.     sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)
  849.     sr.data_encoding = data_encoding
  850.     sr.file_encoding = file_encoding
  851.     return sr
  852.  
  853.  
  854. def getencoder(encoding):
  855.     ''' Lookup up the codec for the given encoding and return
  856.         its encoder function.
  857.  
  858.         Raises a LookupError in case the encoding cannot be found.
  859.  
  860.     '''
  861.     return lookup(encoding).encode
  862.  
  863.  
  864. def getdecoder(encoding):
  865.     ''' Lookup up the codec for the given encoding and return
  866.         its decoder function.
  867.  
  868.         Raises a LookupError in case the encoding cannot be found.
  869.  
  870.     '''
  871.     return lookup(encoding).decode
  872.  
  873.  
  874. def getincrementalencoder(encoding):
  875.     """ Lookup up the codec for the given encoding and return
  876.         its IncrementalEncoder class or factory function.
  877.  
  878.         Raises a LookupError in case the encoding cannot be found
  879.         or the codecs doesn't provide an incremental encoder.
  880.  
  881.     """
  882.     encoder = lookup(encoding).incrementalencoder
  883.     if encoder is None:
  884.         raise LookupError(encoding)
  885.     
  886.     return encoder
  887.  
  888.  
  889. def getincrementaldecoder(encoding):
  890.     """ Lookup up the codec for the given encoding and return
  891.         its IncrementalDecoder class or factory function.
  892.  
  893.         Raises a LookupError in case the encoding cannot be found
  894.         or the codecs doesn't provide an incremental decoder.
  895.  
  896.     """
  897.     decoder = lookup(encoding).incrementaldecoder
  898.     if decoder is None:
  899.         raise LookupError(encoding)
  900.     
  901.     return decoder
  902.  
  903.  
  904. def getreader(encoding):
  905.     ''' Lookup up the codec for the given encoding and return
  906.         its StreamReader class or factory function.
  907.  
  908.         Raises a LookupError in case the encoding cannot be found.
  909.  
  910.     '''
  911.     return lookup(encoding).streamreader
  912.  
  913.  
  914. def getwriter(encoding):
  915.     ''' Lookup up the codec for the given encoding and return
  916.         its StreamWriter class or factory function.
  917.  
  918.         Raises a LookupError in case the encoding cannot be found.
  919.  
  920.     '''
  921.     return lookup(encoding).streamwriter
  922.  
  923.  
  924. def iterencode(iterator, encoding, errors = 'strict', **kwargs):
  925.     '''
  926.     Encoding iterator.
  927.  
  928.     Encodes the input strings from the iterator using a IncrementalEncoder.
  929.  
  930.     errors and kwargs are passed through to the IncrementalEncoder
  931.     constructor.
  932.     '''
  933.     encoder = getincrementalencoder(encoding)(errors, **kwargs)
  934.     for input in iterator:
  935.         output = encoder.encode(input)
  936.         if output:
  937.             yield output
  938.             continue
  939.     
  940.     output = encoder.encode('', True)
  941.     if output:
  942.         yield output
  943.     
  944.  
  945.  
  946. def iterdecode(iterator, encoding, errors = 'strict', **kwargs):
  947.     '''
  948.     Decoding iterator.
  949.  
  950.     Decodes the input strings from the iterator using a IncrementalDecoder.
  951.  
  952.     errors and kwargs are passed through to the IncrementalDecoder
  953.     constructor.
  954.     '''
  955.     decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  956.     for input in iterator:
  957.         output = decoder.decode(input)
  958.         if output:
  959.             yield output
  960.             continue
  961.     
  962.     output = decoder.decode('', True)
  963.     if output:
  964.         yield output
  965.     
  966.  
  967.  
  968. def make_identity_dict(rng):
  969.     ''' make_identity_dict(rng) -> dict
  970.  
  971.         Return a dictionary where elements of the rng sequence are
  972.         mapped to themselves.
  973.  
  974.     '''
  975.     res = { }
  976.     for i in rng:
  977.         res[i] = i
  978.     
  979.     return res
  980.  
  981.  
  982. def make_encoding_map(decoding_map):
  983.     ''' Creates an encoding map from a decoding map.
  984.  
  985.         If a target mapping in the decoding map occurs multiple
  986.         times, then that target is mapped to None (undefined mapping),
  987.         causing an exception when encountered by the charmap codec
  988.         during translation.
  989.  
  990.         One example where this happens is cp875.py which decodes
  991.         multiple character to \\u001a.
  992.  
  993.     '''
  994.     m = { }
  995.     for k, v in decoding_map.items():
  996.         if v not in m:
  997.             m[v] = k
  998.             continue
  999.         m[v] = None
  1000.     
  1001.     return m
  1002.  
  1003.  
  1004. try:
  1005.     strict_errors = lookup_error('strict')
  1006.     ignore_errors = lookup_error('ignore')
  1007.     replace_errors = lookup_error('replace')
  1008.     xmlcharrefreplace_errors = lookup_error('xmlcharrefreplace')
  1009.     backslashreplace_errors = lookup_error('backslashreplace')
  1010. except LookupError:
  1011.     strict_errors = None
  1012.     ignore_errors = None
  1013.     replace_errors = None
  1014.     xmlcharrefreplace_errors = None
  1015.     backslashreplace_errors = None
  1016.  
  1017. _false = 0
  1018. if _false:
  1019.     import encodings
  1020.  
  1021. if __name__ == '__main__':
  1022.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  1023.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  1024.  
  1025.